class Solution(object):
    def numberOfCleanRooms(self, room):
        m = len(room)
        n = len(room[0])
        room_state = [[[0 for _ in range(n)] for _ in range(m)] for _ in range(4)]
        cleaned = [[0 for _ in range(n)] for _ in range(m)]
        x = 0
        y = 0
        state = 0
        while not room_state[state][x][y]:
            room_state[state][x][y] = 1
            cleaned[x][y] = 1
            if state == 0:
                if y < n - 1 and not room[x][y + 1]:
                    y += 1
                else:
                    state = 1
            else:
                if state == 1:
                    if x < m - 1 and not room[x + 1][y]:
                        x += 1
                    else:
                        state = 2
                else:
                    if state == 2:
                        if y > 0 and not room[x][y - 1]:
                            y -= 1
                        else:
                            state = 3
                    else:
                        if x > 0 and not room[x - 1][y]:
                            x -= 1
                        else:
                            state = 0
        return sum([sum([cleaned[x][y] for y in range(n)]) for x in range(m)])